﻿using System;
using System.IO;
using Comdiv.QWeb.Files;
using Comdiv.QWeb.Logging;
using NUnit.Framework;

namespace Comdiv.QWeb.Test.SystemActions
{
	[TestFixture]
	public class get_resource_url_test
	{
		private string dir;
		private QWebContext ctx;
		private FileNameResolver res;
		private TextWriterLogListener log;

		[SetUp]
		public void setup() {
			this.dir = Path.Combine(Path.GetTempPath(), "get_resource_url_test");
			if(Directory.Exists(dir))Directory.Delete(dir,true);
			Directory.CreateDirectory(dir);
			this.ctx = new QWebContext {Uri=new Uri("http://localhost/app/resource/geturl.string.qweb"), RootDirectory = dir, ApplicationName = "/app"};
			this.res = new FileNameResolver();
			
			write("~/usr/scripts/a-en.js","a-english");
			write("~/sys/scripts/a-ru.js", "a-russian");
			write("~/scripts/a.js", "a-default");
			write("~/scripts/path/a.js", "pathed-a-default");
			write("~/images/a.png", "a-png");
			write("~/usr/images/b.gif", "b-gif");
			write("~/sys/c.jpg", "c-jpg");
			write("~/x.css", "x-css");
			write("~/usr/images/y.css", "y-css-not-for-found");
			write("~/sys/styles/y.css", "y-css-for-found");
		}
		[Test]
		public void default_js_resolution() {
			test("a","js","/app/scripts/a.js");
			test("~a", "js", "/app/scripts/a.js");
		}

		[Test]
		public void image_resolution()
		{
			test("a", "img", "/app/images/a.png");
			test("b", "img", "/app/usr/images/b.gif");
			test("c", "img", "/app/sys/c.jpg");
		}


		[Test]
		public void css_resolution()
		{
			test("x", "css", "/app/x.css");
			test("y", "css", "/app/sys/styles/y.css");
		}

		[Test]
		public void default_js_with_culture_resolution()
		{
			test("a", "js","ru-RU", "/app/sys/scripts/a-ru.js");
			test("a", "js", "en-US", "/app/usr/scripts/a-en.js");
			test("a", "js", "zz-ZZ", "/app/scripts/a.js");
		}

		[Test]
		public void default_js_resolution_with_path()
		{
			test("path/a", "js", "/app/scripts/path/a.js");
			test("~path/a", "js", "/app/scripts/path/a.js");
		}

		
		void write(string name, object content) {
			res.Write(name, content, ctx);
		}

		private void test(string name,string type, string expected) {
			test(name, type, null, expected);
		}

		void test(string name,string type, string culture, string expected) {
			if(!string.IsNullOrWhiteSpace(culture)) {
				ctx.Language = culture;
			}
			ctx.Set("name", name).Set("type", type);
			var sw = new StringWriter();
			ctx.Output = sw;
			new QWebHandler().ProcessRequest(ctx);
			Assert.AreEqual(expected, sw.ToString());
		}

	}
}
